import {
  isUniIDError
} from './error'
import {
  getType,
  isPromise
} from './utils'

// 保证各版本clientDB能正常运行
const codeMap = {
  'uni-id-token-expired': 30203,
  'uni-id-check-token-failed': 30202
}

function parseErrMsg (err) {
  const {
    errCode,
    errMsgValue
  } = err
  err.errMsg = this._t(errCode, errMsgValue)
  if (errCode in codeMap) {
    err.code = codeMap[errCode]
  }
  delete err.errMsgValue
}

function isUniIDResponse (res) {
  return getType(res) === 'object' && res.errCode && isUniIDError(res.errCode) && !!res.errCode
}

export function wrapFn (fn) {
  return function () {
    let promise
    try {
      promise = fn.apply(this, arguments)
    } catch (error) {
      if (isUniIDResponse(error)) {
        parseErrMsg.call(this, error)
        return error
      }
      throw error
    }
    if (isPromise(promise)) {
      return promise.then((res) => {
        if (isUniIDResponse(res)) {
          parseErrMsg.call(this, res)
        }
        return res
      }, (err) => {
        if (isUniIDResponse(err)) {
          parseErrMsg.call(this, err)
          return err
        }
        throw err
      })
    } else {
      if (isUniIDResponse(promise)) {
        parseErrMsg.call(this, promise)
      }
    }
    return promise
  }
}
